package com.itheima.reggie.exception;

import com.itheima.reggie.common.R;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;

import java.sql.SQLIntegrityConstraintViolationException;

/*
* 全局异常处理
* */

@ControllerAdvice(annotations = {RestController.class, Controller.class})
@ResponseBody
@Slf4j
public class GlobalExceptionHandler {

    @ExceptionHandler(SQLIntegrityConstraintViolationException.class)
    public R<String> exceptionHandler(SQLIntegrityConstraintViolationException e){
        log.info(e.getMessage());
        //判断异常信息   Duplicate entry 'zhangsan' for key 'idx_username'  切割
        if (e.getMessage().contains("Duplicate entry")){
            String[] split = e.getMessage().split(" ");
            String msg = split[2]+"已存在";
            return R.error("添加失败,"+msg);
        }
        return R.error("未知错误");
    }


    /*
    * 异常处理
    * */
    @ExceptionHandler(CustomException.class)
    public R<String> handlerRuntimeException(CustomException e){
        log.error(e.getMessage());
        return R.error(e.getMessage());

    }
}
